package com.bob.imdservice.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bob.imdservice.AppConstants;
import com.bob.imdservice.R;
import com.bob.imdservice.aidl.SocketMDService;
import com.bob.imdservice.socket.ConnectServer;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private TextView tv_show;
    private Button btn_connect;
    private ScrollView sv_transaction;
    private LinearLayout lv_container;


    private MaterialDialog mMaterialDialog;
    private ConnectServer mConnectServer;
    private SocketMDService mSocketMDService;

    private MessageReceiver mMessageReceiver;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mSocketMDService = SocketMDService.Stub.asInterface(iBinder);
            if (mSocketMDService!=null){
                System.out.println("连接服务");
                tv_show.setText("已连接到远程服务");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mSocketMDService = null;
            System.out.println("断开服务");
            tv_show.setText("已断开到远程服务");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = (TextView) findViewById(R.id.tv_show);
        btn_connect = (Button) findViewById(R.id.btn_connect);
        sv_transaction = (ScrollView) findViewById(R.id.sv_transaction);
        lv_container = (LinearLayout) findViewById(R.id.lv_container);

        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //                    new ConnectServer().service();
                try {
                    mSocketMDService.connectServer();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                tv_show.setText("移动服务器运行中...");
                btn_connect.setText("移动服务器运行中...");
            }
        });
        //TODO: 获取权限
        checkMountPermission();
        mMessageReceiver = new MessageReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstants.BCR_COMMAND);
        intentFilter.addAction(AppConstants.BCR_RECEIVE);
        registerReceiver(mMessageReceiver,intentFilter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        final Intent in = new Intent();
        in.setClassName(this, "com.bob.imdservice.aidl.IMDService");
        in.setPackage("com.bob.imdservice.aidl");
        in.setAction("com.bob.imdservice.aidl.IMDService");
        bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mServiceConnection!=null){
            unbindService(mServiceConnection);
        }
    }

    //先去申请存储权限
    private void checkMountPermission() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this,perms)){
           //TODO: 已有权限
        }else {
            EasyPermissions.requestPermissions(this,"需要存储权限，亲",100,perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
            finish();
        }
    }

    //TODO: 副屏显示二维码需要sd卡权限
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms)){
            askPermissions();
        }
    }

    //TODO: 弹出权限请求自定义Dialog
    private void askPermissions() {
        mMaterialDialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content("手动打开存储权限")
                .positiveText("设置")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        goSetting(101);
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        //如果再次取消则退出
                        finish();
                    }
                })
                .show();
    }

    //去手动设置
    private void goSetting(int requestCode) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //再次处理权限请求结果
        checkMountPermission();
        super.onActivityResult(requestCode, resultCode, data);
    }

    //TODO: 主线程UI消息处理
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    TextView tv_msg = new TextView(MainActivity.this);
                    tv_msg.setText((String)msg.obj);
                    tv_msg.setTextSize(13);
                    lv_container.setOrientation(LinearLayout.VERTICAL);
                    lv_container.addView(tv_msg);
                    sv_transaction.scrollBy(0, 30);
                    break;
                case 1:
                    tv_msg = new TextView(MainActivity.this);
                    tv_msg.setText((String)msg.obj);
                    tv_msg.setTextSize(13);
                    lv_container.setOrientation(LinearLayout.VERTICAL);
                    lv_container.addView(tv_msg);
                    sv_transaction.scrollBy(0, 30);
                    break;
                default:
                    break;
            }
        }
    };

    private class MessageReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                //TODO: 执行命令类
                case AppConstants.BCR_COMMAND:
                    String msg = (String) intent.getExtras().getSerializable("msg");
                    Message message = new Message();
                    message.what = 0;
                    message.obj = msg;
                    mHandler.sendMessage(message);
                    break;
                case AppConstants.BCR_RECEIVE:
                    msg = (String) intent.getExtras().getSerializable("msg");
                    System.out.println("消息：" + msg);
                    message = new Message();
                    message.what = 1;
                    message.obj = msg;
                    mHandler.sendMessage(message);
                    break;
                default:
                    break;
            }
        }
    }
}
